package com.peanut.baby.db;

import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.peanut.baby.InitManager;
import com.peanut.baby.model.AppMsg;
import com.peanut.baby.model.CalendarRecord;
import com.peanut.baby.model.TaskDBRecord;
import com.peanut.devlibrary.util.StringUtil;
import com.tencent.mars.xlog.Log;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by anonymouslystudio on 2017/7/11.
 */

public class DBManager {
    private static final String TAG = DBManager.class.getSimpleName();
    private SQLiteDatabase  db;
    private DBHelper        helper;

    private DBManager(){}
    private static final class InstanceHolder{
        public static final DBManager _instance = new DBManager();
    }

    public static DBManager getInstance(){
        return InstanceHolder._instance;
    }

    /**
     * get database instance
     * @return
     */
    public SQLiteDatabase getDatabase(){
        if(db == null){
            if(getHelper() != null){
                db = getHelper().getWritableDatabase();
            }

        }
        return db;
    }

    /**
     *
     * @return
     */
    public DBHelper getHelper(){
        if(helper == null){
            helper = new DBHelper(InitManager.getInstance().getCtx(),DBConfig.DB_NAME,null,DBConfig.DB_VERSION);
        }
        return helper;
    }

    /**
     *
     * @param sql
     */
    public boolean  exec(String sql){
        try {
            if(!StringUtil.isNullOrEmpty(sql) && getDatabase() != null){
                getDatabase().execSQL(sql);
                return true;
            }
        } catch (SQLException e) {

        }
        return false;
    }

    /**
     *
     * @param sql
     * @return
     */
    public Cursor query(String sql){
        Cursor cursor = null;
        if(!StringUtil.isNullOrEmpty(sql) && getDatabase() != null){
            cursor = getDatabase().rawQuery(sql,null);
        }
        return cursor;
    }

    /**
     *
     * @param sql
     * @param args
     * @return
     */
    public Cursor query(String sql,String[] args){
        Cursor cursor = null;
        if(!StringUtil.isNullOrEmpty(sql) && getDatabase() != null){
            cursor = getDatabase().rawQuery(sql,args);
        }
        return cursor;
    }

    private void closeCursor(Cursor cursor){
        if(cursor != null){
            if(!cursor.isClosed()){
                cursor.close();
            }
            cursor = null;
        }
    }

    public void closeDB(){
        if(db != null){
            if(db.isOpen()){
                db.close();
            }
            db = null;
        }
    }

    public boolean isMsgHasReadedRecord(AppMsg msg){
        String sql = "select * from msg where msgId="+msg.id+";";
        Cursor cursor = query(sql);
        if(cursor != null && cursor.getCount() > 0){
            closeCursor(cursor);
            return true;
        }
        return false;
    }

    public boolean insertMsgReadedFlag(AppMsg msg){
        String sql = "insert into  msg values(null,"+msg.id+");";
        return exec(sql);
    }

    public TaskDBRecord getTaskRecord(int userId,String date) {
        String sql = "select * from task where uid=" + userId + " and date='" + date + "'";
        Cursor cursor = query(sql);

        TaskDBRecord config = new TaskDBRecord();
        config.userId = userId;
        config.date = date;

        if (cursor != null && cursor.getCount() > 0){
            cursor.moveToFirst();
            int sendMoment = cursor.getInt(cursor.getColumnIndex("send_moment"));
            int replyMoment = cursor.getInt(cursor.getColumnIndex("reply_moment"));
            int shareMoment = cursor.getInt(cursor.getColumnIndex("share_moment"));
            int shareLive = cursor.getInt(cursor.getColumnIndex("share_live"));
            int shareQA = cursor.getInt(cursor.getColumnIndex("share_qa"));
            int shareApp = cursor.getInt(cursor.getColumnIndex("share_app"));

            config.sendMomentCount = sendMoment;
            config.replyMomentCount = replyMoment;
            config.shareMomentCount = shareMoment;
            config.shareLiveCount = shareLive;
            config.shareQACount = shareQA;
            config.shareAppCount = shareApp;


        }
        closeCursor(cursor);
        Log.d(TAG,"getTaskRecord:"+config.toString());
        return config;
    }

    public void updateTaskRecord(TaskDBRecord newRecord){
        Log.d(TAG,"updateTaskRecord: "+newRecord.toString());
        String sql = "select * from task where uid=" + newRecord.userId + " and date='" + newRecord.date + "'";
        Cursor cursor = query(sql);

        if (cursor != null && cursor.getCount() > 0){
            Log.d(TAG,"updateTaskRecord already has record , update to new");
            sql = "update task set send_moment="+newRecord.sendMomentCount+"," +
                    " reply_moment="+newRecord.replyMomentCount+", share_moment="+newRecord.shareMomentCount+"," +
                    " share_live="+newRecord.shareLiveCount+", share_qa="+newRecord.shareQACount+", share_app="+newRecord.shareAppCount+" " +
                    " where uid="+newRecord.userId+" and date='"+newRecord.date+"'";
            Log.d(TAG,"\t\tupdate sql: "+sql);
        }else{
            Log.d(TAG,"updateTaskRecord has no record, insert new record");
            sql = "insert into task values(null,"+newRecord.userId+",'"+newRecord.date+"',"+newRecord.sendMomentCount+","+newRecord.replyMomentCount+","+newRecord.shareMomentCount+"," +
                    ""+newRecord.shareLiveCount+","+newRecord.shareQACount+","+newRecord.shareAppCount+");";
            Log.d(TAG,"\t\tinsert sql: "+sql);
        }
        getDatabase().execSQL(sql);
        closeCursor(cursor);

    }

    //记录
    public CalendarRecord getCalendarRecord(int userId, String date) {
        String sql = "select * from calendar where uid=" + userId + " and date='" + date + "'";
        Cursor cursor = query(sql);

        CalendarRecord config = null;

        if (cursor != null && cursor.getCount() > 0){
            cursor.moveToFirst();
            String dayima = cursor.getString(cursor.getColumnIndex("dayima"));
            String tongfang = cursor.getString(cursor.getColumnIndex("tongfang"));
            String tiwen = cursor.getString(cursor.getColumnIndex("tiwen"));
            String yesuan = cursor.getString(cursor.getColumnIndex("yesuan"));
            String baidai = cursor.getString(cursor.getColumnIndex("baidai"));

            String dayimaValue = dayima;
            if(dayimaValue.equals("是")){
                dayimaValue = "来了";
            }else if(dayimaValue.equals("否")){
                dayimaValue = "走了";
            }


            config = new CalendarRecord();
            config.userId = userId;
            config.date = date;
            config.dayima = dayimaValue;
            config.tongfang = tongfang;
            config.tiwen = tiwen;
            config.yesuan = yesuan;
            config.baidai = baidai;

        }
        closeCursor(cursor);
        Log.d(TAG,"getCalendarRecord:"+config == null?"null":"not null");
        return config;
    }

    //更新记录
    public void updateCalendarRecord(CalendarRecord newRecord){

        String dayimaValue = newRecord.dayima;
        if(dayimaValue.equals("是")){
            dayimaValue = "来了";
        }else if(dayimaValue.equals("否")){
            dayimaValue = "走了";
        }
        String sql = "select * from calendar where uid=" + newRecord.userId + " and date='" + newRecord.date + "'";
        Cursor cursor = query(sql);

        if (cursor != null && cursor.getCount() > 0){
            Log.d(TAG,"updateCalendarRecord already has record , update to new");
            sql = "update calendar set dayima='"+dayimaValue+"'," +
                    " tongfang='"+newRecord.tongfang+"'," +
                    " tiwen='"+newRecord.tiwen+"'," +
                    " yesuan='"+newRecord.yesuan+"'," +
                    " baidai='"+newRecord.baidai+"' where uid="+newRecord.userId+" and date='"+newRecord.date+"'";
            Log.d(TAG,"\t\tupdate sql: "+sql);
        }else{
            Log.d(TAG,"updateCalendarRecord has no record, insert new record");
            sql = "insert into calendar values(null,"+newRecord.userId+"," +
                    "'"+newRecord.date+"'," +
                    "'"+dayimaValue+"'," +
                    "'"+newRecord.tongfang+"'," +
                    "'"+newRecord.tiwen+"'," +
                    "'"+newRecord.yesuan+"'," +
                    "'"+newRecord.baidai+"');";
            Log.d(TAG,"\t\tinsert sql: "+sql);
        }
        getDatabase().execSQL(sql);
        closeCursor(cursor);

    }


    /**
     * 取大姨妈字段有值的记录
     * @param userId
     * @return
     */
    public List<CalendarRecord> getCalendarRecordWithMense(int userId) {
        String sql = "select * from calendar where uid=" + userId + " and dayima !=''";
        Cursor cursor = query(sql);

        List<CalendarRecord> configs= null;

        if (cursor != null && cursor.getCount() > 0){
            configs = new ArrayList<>();
            cursor.moveToFirst();
            while(!cursor.isAfterLast()){
                CalendarRecord config = new CalendarRecord();

                String date = cursor.getString(cursor.getColumnIndex("date"));
                String dayima = cursor.getString(cursor.getColumnIndex("dayima"));
                String tongfang = cursor.getString(cursor.getColumnIndex("tongfang"));
                String tiwen = cursor.getString(cursor.getColumnIndex("tiwen"));
                String yesuan = cursor.getString(cursor.getColumnIndex("yesuan"));
                String baidai = cursor.getString(cursor.getColumnIndex("baidai"));

                config.userId = userId;
                config.date = date;
                config.dayima = dayima;
                config.tongfang = tongfang;
                config.tiwen = tiwen;
                config.yesuan = yesuan;
                config.baidai = baidai;

                configs.add(config);

                cursor.moveToNext();
            }
        }
        closeCursor(cursor);
        Log.d(TAG,"getCalendarRecordWithMense:"+configs == null?"null":" has record "+configs.size());
        return configs;
    }

    public List<CalendarRecord> getAllCalendarRecord(int userId) {
        String sql = "select * from calendar where uid=" + userId + "";
        Cursor cursor = query(sql);

        List<CalendarRecord> configs= null;

        if (cursor != null && cursor.getCount() > 0){
            configs = new ArrayList<>();
            cursor.moveToFirst();
            while(!cursor.isAfterLast()){
                CalendarRecord config = new CalendarRecord();

                String date = cursor.getString(cursor.getColumnIndex("date"));
                String dayima = cursor.getString(cursor.getColumnIndex("dayima"));
                String tongfang = cursor.getString(cursor.getColumnIndex("tongfang"));
                String tiwen = cursor.getString(cursor.getColumnIndex("tiwen"));
                String yesuan = cursor.getString(cursor.getColumnIndex("yesuan"));
                String baidai = cursor.getString(cursor.getColumnIndex("baidai"));

                if(!StringUtil.isNullOrEmpty(dayima)
                        || !StringUtil.isNullOrEmpty(tongfang)
                        || !StringUtil.isNullOrEmpty(tiwen)
                        || !StringUtil.isNullOrEmpty(yesuan)
                        || !StringUtil.isNullOrEmpty(baidai)){
                    config.userId = userId;
                    config.date = date;
                    config.dayima = dayima;
                    config.tongfang = tongfang;
                    config.tiwen = tiwen;
                    config.yesuan = yesuan;
                    config.baidai = baidai;

                    configs.add(config);

                }
                cursor.moveToNext();
            }
        }
        closeCursor(cursor);
        Log.d(TAG,"getAllCalendarRecord:"+(configs == null? "null":" has record "+configs.size()));
        return configs;
    }
}
